package com.chen.palmar.project.set;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.constant.AppConstant;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.chen.palmar.common.widget.view.CircleImageView;
import com.chen.palmar.entity.UserInfoEntity;
import com.flyco.dialog.widget.NormalDialog;
import com.primb.androidlibs.net.entity.HttpResultEntity;
import com.primb.androidlibs.net.entity.MessageEvent;
import com.primb.androidlibs.utils.FileUtils;
import com.primb.androidlibs.utils.ImageUtils;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import io.valuesfeng.picker.ImageSelectActivity;
import io.valuesfeng.picker.Picker;
import io.valuesfeng.picker.engine.GlideEngine;
import rx.Subscription;

/**
 * @author Chen
 * @date 2018/1/8
 * 功能描述：
 */

public class AccountManagerActivity extends BaseActivity {

    private static final int REQUEST_CODE_IMG = 21;
    private static final int REQUEST_CODE_NAME = 22;
    private static final int REQUEST_CODE_PHONE = 23;
    public static final int EVENT_ACCOUNT_CODE = 100;
    @Bind(R.id.title_bar)
    TextView titleBar;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.iv_user_head)
    CircleImageView ivUserHead;
    @Bind(R.id.tv_user_name)
    TextView tvUserName;
    @Bind(R.id.tv_user_phone)
    TextView tvUserPhone;
    private UserInfoEntity.DataBean info;
    private Uri uri;
    private String savePath = Environment.getExternalStorageDirectory().getPath() + AppConstant.LOAD_CACHE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public void init() {
        info = (UserInfoEntity.DataBean) getIntent().getSerializableExtra("info");

        toolBar.setNavigationOnClickListener(v -> {
            if (uri != null) {
                NormalDialog dialog = showAlterDialog("修改头像", "确定修改上传新头像？");
                dialog.btnText("取消修改", "确定修改");
                dialog.setOnBtnClickL(() -> {
                    dialog.dismiss();
                    Picasso.with(this).load(info.getAvatar()).placeholder(R.mipmap.set_head_icon).error(R.mipmap.set_head_icon).into(ivUserHead);
                    uri = null;
                    AccountManagerActivity.this.finish();
                }, () -> {
                    dialog.dismiss();
                    uploadHead();
                });
            } else {
                AccountManagerActivity.this.finish();
            }
        });

        titleBar.setText("账户管理");

        if (TextUtils.isEmpty(info.getMobile())) {
            tvUserPhone.setText("未绑定");
        } else {
            tvUserPhone.setText(info.getMobile());
        }

        if (TextUtils.isEmpty(info.getName())) {
            tvUserName.setText(info.getUserId() + "");
        } else {
            tvUserName.setText(info.getName());
        }
        if (TextUtils.isEmpty(info.getAvatar())) {
            Picasso.with(this).load(R.mipmap.set_head_icon).placeholder(R.mipmap.set_head_icon).error(R.mipmap.set_head_icon).fit().into(ivUserHead);
        } else {
            Picasso.with(this).load(info.getAvatar()).placeholder(R.mipmap.set_head_icon).error(R.mipmap.set_head_icon).fit().into(ivUserHead);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_accout_manager;
    }

    @OnClick({R.id.iv_user_head, R.id.tv_user_name, R.id.tv_user_phone, R.id.tv_user_pwd})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.iv_user_head:
                Picker.from(this).singleChoice().enableCamera(true).setEngine(new GlideEngine()).forResult(REQUEST_CODE_IMG);
                break;
            case R.id.tv_user_name:
                intent.setClass(this, EditNameActivity.class);
                intent.putExtra("info", info.getName());
                startActivityForResult(intent, REQUEST_CODE_NAME);
                break;
            case R.id.tv_user_phone:
                intent.setClass(this, EditPhoneActivity.class);
                intent.putExtra("info", info.getMobile());
                startActivityForResult(intent, REQUEST_CODE_PHONE);
                break;
            case R.id.tv_user_pwd:
                intent.setClass(this, EditPwdActivity.class);
                intent.putExtra("info", info.getMobile());
                startActivity(intent);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && uri != null) {
            NormalDialog dialog = showAlterDialog("修改头像", "确定修改上传新头像？");
            dialog.btnText("取消修改", "确定修改");
            dialog.setOnBtnClickL(() -> {
                dialog.dismiss();
                Picasso.with(this).load(info.getAvatar()).placeholder(R.mipmap.set_head_icon).error(R.mipmap.set_head_icon).into(ivUserHead);
                uri = null;
                AccountManagerActivity.this.finish();
            }, () -> {
                dialog.dismiss();
                uploadHead();
            });
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void uploadHead() {
        File imgFile = new File(FileUtils.getRealPathFromUri(this, uri));
        File fileCache = new File(savePath);
        if (!fileCache.exists()) {
            fileCache.mkdirs();
        }
        File file = new File(savePath + File.separator + System.currentTimeMillis() + ".jpg");
        try {
            if (file.exists()) {
                file.delete();
                file.createNewFile();
            } else {
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
            file = new File(FileUtils.getRealPathFromUri(this, uri));
        }
        Bitmap src = ImageUtils.getBitmap(imgFile);
        Bitmap bitmap = ImageUtils.centerSquareScaleBitmap(src, Math.min(src.getWidth(), src.getHeight()));
        boolean recycled = bitmap.isRecycled();
        boolean save = ImageUtils.save(bitmap, file, Bitmap.CompressFormat.JPEG);
        Subscription subscribe = DataCenter.editUserHead(file).subscribe(new HttpSubscriber<HttpResultEntity>(this, showLoading()) {
            @Override
            public void onNext(HttpResultEntity httpResultEntity) {
                //                showToast(httpResultEntity.getMessage());
                EventBus.getDefault().post(new MessageEvent(EVENT_ACCOUNT_CODE));
                AccountManagerActivity.this.finish();
            }
        });
        subscription.add(subscribe);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_IMG && resultCode == Activity.RESULT_OK) {
            List<Uri> imgList = data.getParcelableArrayListExtra(ImageSelectActivity.EXTRA_RESULT_SELECTION);
            uri = imgList.get(0);
            Picasso.with(this).load(uri).placeholder(R.mipmap.set_head_icon).error(R.mipmap.set_head_icon).into(ivUserHead);
        } else if (requestCode == REQUEST_CODE_NAME && resultCode == Activity.RESULT_OK) {
            String info = data.getStringExtra("info");
            tvUserName.setText(info);
            EventBus.getDefault().post(new MessageEvent(EVENT_ACCOUNT_CODE));
        } else if (requestCode == REQUEST_CODE_PHONE && resultCode == Activity.RESULT_OK) {
            String info = data.getStringExtra("info");
            tvUserPhone.setText(info);
            EventBus.getDefault().post(new MessageEvent(EVENT_ACCOUNT_CODE));
        }
    }
}
